#!/bin/sh
# MeshWatch Console team server — run the six products as a service and open the
# console from any browser on your network (https://<this server>:8444/).
#
# The packaged `meshwatch-console` binary is Electron, and Electron is also a
# complete Node.js. With ELECTRON_RUN_AS_NODE=1 it runs a plain script: no X server,
# no GPU, no window. The script is the team server entry point inside app.asar.
#
#   "/opt/MeshWatch Console/meshwatch-console-server"             # foreground
#   "/opt/MeshWatch Console/meshwatch-console-server" --help      # options
#   "/opt/MeshWatch Console/meshwatch-console-server" --show-url  # address + certificate fingerprint
#
# To run it as a service, see meshwatch-console-server.service next to this file.
# readlink -f: /usr/local/bin 의 링크로 불려도(Docker 이미지) 설치 폴더를 찾는다.
here=$(cd "$(dirname "$(readlink -f "$0" 2>/dev/null || echo "$0")")" && pwd)
app="$here/meshwatch-console"

if [ ! -x "$app" ]; then
  echo "meshwatch-console-server: cannot find the MeshWatch Console binary next to this script ($app)." >&2
  exit 1
fi

# The loader resolves every library the binary is linked against before our code runs,
# even though nothing is drawn. Say what is missing instead of a bare loader error.
probe=$(ELECTRON_RUN_AS_NODE=1 "$app" -e "" 2>&1)
probe_status=$?
if [ $probe_status -ne 0 ]; then
  case "$probe" in
    *"error while loading shared libraries"*|*"cannot open shared object file"*)
      echo "meshwatch-console-server: this server is missing libraries the MeshWatch Console" >&2
      echo "runtime is linked against (nothing is drawn, but they must be present)." >&2
      if command -v ldd >/dev/null 2>&1; then
        echo "Missing here:" >&2
        ldd "$app" 2>/dev/null | grep "not found" | awk '{print "    " $1}' | sort -u >&2
      fi
      echo "Debian / Ubuntu:  sudo apt-get install -y libgtk-3-0 libnotify4 libnss3 libxss1 libxtst6 \\" >&2
      echo "                      xdg-utils libatspi2.0-0 libuuid1 libsecret-1-0 libgbm1 libasound2 xvfb" >&2
      echo "                  (Ubuntu 24.04 / Debian trixie: libasound2t64)" >&2
      echo "RHEL / Rocky / Alma / Fedora:  sudo dnf install -y gtk3 libnotify nss libXScrnSaver libXtst \\" >&2
      echo "                      xdg-utils at-spi2-atk libuuid libsecret mesa-libgbm alsa-lib xorg-x11-server-Xvfb" >&2
      exit 1
      ;;
    *)
      echo "meshwatch-console-server: the MeshWatch Console runtime would not start." >&2
      echo "$probe" >&2
      exit $probe_status
      ;;
  esac
fi

# Corporate proxy: the daily version check honours HTTPS_PROXY / NO_PROXY when set.
export NODE_USE_ENV_PROXY=1

ELECTRON_RUN_AS_NODE=1 exec "$app" "$here/resources/app.asar/src/server/main.js" "$@"
